package com.glsc.ngateway.oaflow.schedule;

import com.glsc.ngateway.common.api.common.enums.RabbitExcQueConstant;
import com.glsc.ngateway.common.base.domain.mysql.gateway.oaflow.TOaFlowSubscribeOaFlowInfo;
import com.glsc.ngateway.common.base.domain.oracle.ecology.WorkflowRequestbase;
import com.glsc.ngateway.common.base.enums.OaWorkFlowRequestTableCurrentNodeTypeEnum;
import com.glsc.ngateway.common.base.repo.mysql.gateway.oaflow.TOaFlowSubscribeOaFlowInfoRepository;
import com.glsc.ngateway.common.base.repo.oracle.ecology.WorkflowRequestbaseRepository;
import com.glsc.ngateway.oaflow.utils.MqUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class WatchOaFlowChangeTask {
    private static final Logger logger = LoggerFactory.getLogger(WatchOaFlowChangeTask.class);

    @Resource
    private TOaFlowSubscribeOaFlowInfoRepository subOaFlowInfoRepo;
    @Resource
    private WorkflowRequestbaseRepository workflowRbRepo;

    //@Scheduled(cron = "0 0/1 * * * ?")
    @XxlJob("watchOaFlowChangeTask_watchOaFlowChange")
    public void watchOaFlowChange() {
        //查询所有非终态流程信息
        List<TOaFlowSubscribeOaFlowInfo> subList = subOaFlowInfoRepo.findAllByCurrentNodeTypeNot(OaWorkFlowRequestTableCurrentNodeTypeEnum.END.getCode());
        if (CollectionUtils.isEmpty(subList)) {
            logger.info("监控Oa流程变化：当前无可监控流程");
            return;
        }
        //查询oa流程
        List<Integer> watchReqIds = subList.stream().map(TOaFlowSubscribeOaFlowInfo::getRequestId).collect(Collectors.toList());
        List<WorkflowRequestbase> oaReqList = workflowRbRepo.findAllByRequestidIn(watchReqIds);
        Map<Integer, WorkflowRequestbase> oaReqMap = oaReqList.stream().collect(Collectors.toMap(WorkflowRequestbase::getRequestid, o -> o));
        //对比找出发生变化的
        List<TOaFlowSubscribeOaFlowInfo> changeList = subList.stream()
                .filter(info -> {
                    if (!oaReqMap.containsKey(info.getRequestId())) {
                        return false;
                    }
                    WorkflowRequestbase oaReq = oaReqMap.get(info.getRequestId());
                    if (oaReq.getLastoperatedate() != null && oaReq.getLastoperatetime() != null && oaReq.getLastoperatedate().atTime(oaReq.getLastoperatetime()).equals(info.getLastUpdateTime())) {
                        return false;
                    }
                    info.setStatus(oaReq.getStatus());
                    info.setCurrentNodeType(oaReq.getCurrentnodetype());
                    info.setLastUpdateTime(oaReq.getLastoperatedate().atTime(oaReq.getLastoperatetime()));
                    return true;
                })
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(changeList)) {
            logger.info("监控Oa流程变化：当前所有流程均未变化");
            return;
        }
        //发消息通知
        Map<String, Object> msg = new HashMap<>(){{
            put("requestIdList", changeList.stream().map(TOaFlowSubscribeOaFlowInfo::getRequestId).distinct().collect(Collectors.toList()));
        }};
        logger.info("监控Oa流程变化：发送消息msg:", msg);
        MqUtil.sendMessage(RabbitExcQueConstant.GATEWAY_EXCHANGE_FLOW_OA_FLOW_WATCH, RabbitExcQueConstant.GATEWAY_QUEUE_FLOW_OA_FLOW_WATCH_YSP, msg);
        //修改本地库中记录
        subOaFlowInfoRepo.saveAll(changeList);
    }
}